import urllib2
import re
irc = None

title = re.compile(r'(?ims)<title[^>]*>(.*?)</title\s*>')

def init(bot):
    global irc
    bot.cmd.events['PRIVMSG'].subscribe(privmsg)
    irc = bot


def privmsg(sender, args):
    global irc
    mtitle = ""
    msg = args[0].split()
    if "http://" in args[0]:
        moo = args[0].find("http://")
        cow = args[0].find(" ", moo)
        if cow == -1:
            cow = len(args[0])
        link = args[0][moo:cow]
        try:
            request = urllib2.Request(link, headers = {"Accept" : "text/html"})

            data = urllib2.urlopen(request)

            if data.info().type != 'text/html':
                return
            html = data.read()
            data.close()
            topic = title.search(html)
            if topic:
                mtitle = topic.group(1)
                mtitle = mtitle.strip()
                mtitle = mtitle.replace("\t", " ")
                mtitle = mtitle.replace("\r", " ")
                mtitle = mtitle.replace("\n", " ")
                mtitle = mtitle.replace("\x03", "")
                if len(mtitle) > 175:
                    mtitle = mtitle[:175] + "..."
        except:
            mtitle = "Could not connect to that site"
        
        # don't print the link back out... chaos ensues with more than one bot
        irc.privmsg(args[2], "%s: <Title> %s" % (sender.nick, mtitle))
